package com.yuanfeng.base.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.base.dto.ModularizationdDTO;
import com.yuanfeng.base.entity.BaseModularizationdEntity;
import com.yuanfeng.base.feign.ActivityClient;
import com.yuanfeng.base.mapper.BaseModularizationdMapper;
import com.yuanfeng.base.service.BaseModularizationdService;
import com.yuanfeng.base.vo.ModularizationdGoodsVO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.Json.JsonUtils;
import com.yuanfeng.commoms.util.ParseMapUtils;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.activity.ModularGoodsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName BaseModularizationdServiceImpl
 * @Description  组件化 页面
 * @Author ty
 * @Date 2023-07-04 17:58:52
 * @Version 1.0
 **/
@Service
public class BaseModularizationdServiceImpl extends ServiceImpl<BaseModularizationdMapper, BaseModularizationdEntity> 
        implements BaseModularizationdService {
    @Autowired
    private ActivityClient activityClient;

    @Override
    public ResponseResult ModularizationdAddOrUPdate(ModularizationdDTO param) {
        Integer result = null;
        try {
            if(null == param.getPageType()){
                param.setPageType(0);
            }
            if(null == param.getPageId()){ //添加或修改
                if(null != param.getGoodsAllId() && param.getGoodsAllId().size() > 0){
                    param.setGoodsAllIdJson(JsonUtils.toString(param.getGoodsAllId()));
                }
                if(null != param.getPageIsIndex() && 2 == param.getPageIsIndex()){//判断是否是二级页面
                    param.setPageStart(1);
                }else{
                    param.setPageStart(0);
                }
                result =  this.baseMapper.addModularizationd(param);
                if(0 == result){
                    return ResponseResult.fail();
                }
            }else{
                if(null != param.getGoodsAllId() && param.getGoodsAllId().size() > 0){
                    param.setGoodsAllIdJson(JsonUtils.toString(param.getGoodsAllId()));
                }
                result =  this.baseMapper.updateModularizationd(param);
                if(0 == result){
                    return ResponseResult.fail();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.success();
    }

    @Override
    public ResponseResult queryModularizationdAll(ModularizationdDTO param) {
        Map map = null;
        try {
            map = ParseMapUtils.beanToMap(param);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        IPage<ModularizationdDTO> page = this.baseMapper.queryModularizationdAll(new Query<ModularizationdDTO>().getPage(map),param);
        List<ModularizationdDTO> records = page.getRecords();
        if(null != param.getPageIsIndex() && 2 == param.getPageIsIndex()){//判断是否是二级页面
            if(!CollectionUtils.isEmpty(records)){
                for (ModularizationdDTO modularizationdParam : records) {
                    if(null != modularizationdParam.getPageStart() && 1 == modularizationdParam.getPageStart()){//判断二级页面是否开启 1 开启 0 关闭
                        modularizationdParam.setPageUrl("/general/diy/diy?pageId="+modularizationdParam.getPageId());
                    }
                }
            }
        }
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult queryModularizationdById(ModularizationdDTO param) {
        ModularizationdDTO  modularizationdParam =  this.baseMapper.queryModularizationdById(param);
        List<ModularizationdGoodsVO> modularizationdGoodsParams = queryModularizationdGoodsInfo(modularizationdParam.getGoodsAllIdJson());
        modularizationdParam.setGoodsList(modularizationdGoodsParams);
        return ResponseResult.success(modularizationdParam);
    }

    @Override
    public ResponseResult modularizationdDelete(ModularizationdDTO param) {
        Integer result =  this.baseMapper.modularizationdDelete(param);
        if (result > 0){
            return ResponseResult.success();
        }
        return ResponseResult.fail();
    }

    @Override
    public ResponseResult modularizationdUpdateStart(ModularizationdDTO param) {
        if(null == param.getPageId() || null == param.getPageStart()){
            return ResponseResult.fail(BizCodeEnume.MISSING_PARAMETER.getCode(),BizCodeEnume.MISSING_PARAMETER.getMsg());
        }
        this.baseMapper.updateStartAll();// 将其他的设置为首页的页面 取消设置
        Integer result =  this.baseMapper.UpdateStart(param);
        if (result > 0){
            return ResponseResult.success();
        }
        return ResponseResult.fail();
    }

    @Override
    public ResponseResult ModularizationdDefaultByPageId(ModularizationdDTO param) {
        ModularizationdDTO modularizationdParam = this.baseMapper.queryModularizationdDefault(param);
        return ResponseResult.success(modularizationdParam);
    }

    @Override
    public ResponseResult UpdateSecondLevelStart(ModularizationdDTO param) {
        Integer result = null;
        Integer rr = null;
        try {
            if(null == param.getPageId()){
                return ResponseResult.fail(BizCodeEnume.MISSING_PARAMETER);
            }
            if(null == param.getPageStart()){
                return ResponseResult.fail(BizCodeEnume.MISSING_PARAMETER);
            }
            result =  this.baseMapper.update(null,new LambdaUpdateWrapper<BaseModularizationdEntity>()
                         .set(BaseModularizationdEntity::getPageStart,param.getPageStart())
                         .eq(BaseModularizationdEntity::getPageId,param.getPageId()));
            if(0 == result){
                return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
            }
            return ResponseResult.fail(BizCodeEnume.OPERATION_SUCCESSFUL);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(e.getMessage());
        }
    }

    @Override
    public ResponseResult modularizationdUpdateIndex() {
        try {
            //查询首页数据
            BaseModularizationdEntity modularizationdParam = this.baseMapper.selectOne(new LambdaQueryWrapper<BaseModularizationdEntity>()
                                                             .eq(BaseModularizationdEntity::getPageStart,1)
                                                             .eq(BaseModularizationdEntity::getPageIsIndex,1));
            if(null==modularizationdParam){//如果位null就查询系统默认的页面
                List<BaseModularizationdEntity> modularizationdParams = this.baseMapper.selectList(new LambdaQueryWrapper<BaseModularizationdEntity>()
                                                                    .eq(BaseModularizationdEntity::getPageDefault,1));
                if(null !=modularizationdParams && modularizationdParams.size()!=0){
                    List<ModularizationdGoodsVO> modularizationdGoodsParams = queryModularizationdGoodsInfo(modularizationdParams.get(0).getGoodsallidjson());
                    modularizationdParam.setGoodsList(modularizationdGoodsParams);
                    return ResponseResult.success(modularizationdParams.get(0));
                }
            }
            List<ModularizationdGoodsVO> modularizationdGoodsParams = queryModularizationdGoodsInfo(modularizationdParam.getGoodsallidjson());
            modularizationdParam.setGoodsList(modularizationdGoodsParams);
            return ResponseResult.success(modularizationdParam);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(e.getMessage());
        }
    }
    /**
     *查询组件化页面 商品信息
     */
    public List<ModularizationdGoodsVO> queryModularizationdGoodsInfo(String goodsAllIdJson){
        List<ModularizationdGoodsVO> list = new ArrayList<>();
        if(null == goodsAllIdJson){
            return null;
        }
        List<String> goodsAllIdJsons = JsonUtils.string2Obj(goodsAllIdJson, List.class, String.class);
        for (String goodsId : goodsAllIdJsons) {
            ModularizationdGoodsVO modularizationdGoodsParam;
            //查询商品 价格 销量
            modularizationdGoodsParam = this.baseMapper.queryModularizationdGoodsInfo(goodsId);
            Map<String,Object> activityMap = dealActivityStatus(Integer.parseInt(goodsId));
            if(null == modularizationdGoodsParam){
                modularizationdGoodsParam = new ModularizationdGoodsVO();
                modularizationdGoodsParam.setGoodsStart(2);//商品状态 1 上架 2 下架
                modularizationdGoodsParam.setGoodsId(Integer.valueOf(goodsId));//商品状态 1 上架 2 下架
            }else{
                modularizationdGoodsParam.setGoodsStart(1);//商品状态 1 上架 2 下架
            }
            if(null != activityMap.get("activityStatus") && 1 == (Integer) activityMap.get("activityStatus")){
                modularizationdGoodsParam.setActivityStatus(1);
                if(null != activityMap.get("activityPrice")){
                    modularizationdGoodsParam.setCommonPrice((BigDecimal) activityMap.get("activityPrice"));
                    modularizationdGoodsParam.setStartTime(activityMap.get("startTime").toString());
                    modularizationdGoodsParam.setEndTime( activityMap.get("endTime").toString());
                }
            }else {
                modularizationdGoodsParam.setActivityStatus(2);
            }
            list.add(modularizationdGoodsParam);
        }
        return list;
    }

    /**
     * 处理活动状态
     * @param goodsId
     * @return
     */
    public Map<String,Object>  dealActivityStatus(Integer goodsId){
        Map<String,Object> map = new HashMap<>();
        Integer commonIsXian = null;//活动类型 0不参加,2秒杀,3限时折扣,4拼团,5满减赠折
        BigDecimal activityPrice = new BigDecimal(0);//参见活动的商品价格 加为空，证明改商品的是未参加活动 或活动以过期
        ModularGoodsVO modularGoodsParam=null;
        try {
            commonIsXian = this.baseMapper.queryCommonIsXian(goodsId);
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        if(null == commonIsXian || 0 == commonIsXian){//普通商品
            map.put("activityStatus",0);//活动状态 0-结束 1-正常
            return map;
        }else if(2 == commonIsXian){//秒杀商品
            modularGoodsParam = JSONObject.parseObject(JSON.toJSONString(activityClient.seckillGoodsPrice(goodsId).getData()),ModularGoodsVO.class);

        }else if(3 == commonIsXian){//限时折扣商品
            modularGoodsParam = JSONObject.parseObject(JSON.toJSONString(activityClient.selectPriceByGoodsId(goodsId).getData()),ModularGoodsVO.class);

        }else if(4 == commonIsXian){//拼团商品
            modularGoodsParam = JSONObject.parseObject(JSON.toJSONString(activityClient.pinTuanGoodsPrice(goodsId).getData()),ModularGoodsVO.class);

        }else if(5 == commonIsXian){//满减赠折商品
            modularGoodsParam = JSONObject.parseObject(JSON.toJSONString(activityClient.manJianZengZheGoodsPrice(goodsId).getData()),ModularGoodsVO.class);

        }
        if(null != modularGoodsParam && null != modularGoodsParam.getActivityPrice() && 0 <= modularGoodsParam.getActivityPrice().compareTo(BigDecimal.ZERO)){//如果活动价 不为null 且大于0 证明该活动未过期
            map.put("activityStatus",1);//活动状态 0-结束 1-正常
            map.put("activityPrice",modularGoodsParam.getActivityPrice());//活动状态 0-结束 1-正常
            map.put("startTime",modularGoodsParam.getStartTime());
            map.put("endTime",modularGoodsParam.getEndTime());
        }else{
            map.put("activityStatus",0);//活动状态 0-结束 1-正常
        }
        return map;
    }
}
